'use strict'
//引入相关模块
const ws = require('nodejs-websocket');
//ws服务
let server = null
// 建立服务并记录加入的客户端
let clientCount = 0;
function startWs(port = 5277) {
    server = ws.createServer(function (conn) {
        console.log("New connection")
        clientCount++;
        conn.nickname = 'user' + clientCount;
        conn.on("text", function (str) {
            console.log("Received " + str);
            broadcast(conn, str);
            conn.send("OK");
        })
        conn.on("close", function (code, reason) {

        })
        conn.on("error", function (err) {
            console.log("handle err");
            console.log(err);
        })
    }).listen(port);
    console.log("websocket server running on port: " + port);

}
//对连接在该服务的所有链接进行消息广播
function broadcast(conn, str) {
    server.connections.forEach(function (connection) {
        if (connection.nickname != conn.nickname) {
            console.log("broadcast=" + str);
            connection.send(str);
        }
    })
}
module.exports = { startWs }

